var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var wxcache = require('../../../utils/wxcache.js');
var user = require('../../../services/user.js');
var app = getApp();
Page({
  data: {
    username: '',
    password: '',
    dyanmicCode:'',
    code: '',
    loginErrorCount: 0,
    seqNo: '', //短信唯一id
    vcode: '', //短信验证码
    ajxtrue:false,//手机号验证是否正确
    dyanmicCodeNumber:'60',
    dyanmicCodeNumbers: 60,
    _num:0,
    _num0:0,
    _num2:1,
    forgetOrPasswordLoad:'验证码登录',
    loginType:'',
    isNewPerson:2,
    isHasPassword:2,

    changeLoginFlag:true, //默认微信登陆
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // 页面渲染完成
    if (options.type){
      this.setData({
        loginType: options.type
      });
    }  
  },
  onReady: function () {

  },
  onShow: function () {
      
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  // 切换微信登陆方式
  wxLogin:function(e){
    this.setData({
      changeLoginFlag : true
    })
  },
  // 手机号登陆
  phoneLogin: function (e) {
    this.setData({
      changeLoginFlag :false
    })
  },


  //解密手机号
  getPhoneNumber: function (e) {
    console.log(e)
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)

    if (!e.detail.encryptedData){
      wx.showModal({
        content: '需要获取您的授权才可登陆喔~',
        showCancel:false
      })
      return;
    }

    //判断session 是否过期
    wx.checkSession({
      success: function(){
          var data={}
          data.encryptedData = e.detail.encryptedData
          data.iv = e.detail.iv
          data.thirdSessionId = wxcache.get('token');
          console.log(data)
          util.request(api.GetDecodeUserInfo,data,'POST').then(function(res){
            
              console.log(res)
             //将手机号放入缓存
              wxcache.put("phoneNumber", (res.responseBody.phoneNumber));
              var isNewPerson = res.responseBody.newPeople;

              util.request(api.QueryUserInfo, { mobile: res.responseBody.phoneNumber })
                .then(function (res) {
                var tmp = res.responseBody;
                //如果是新用户或者 之前用手机号登陆未初始个人信息
                if (isNewPerson || !tmp.nickName || !tmp.openId) {

                  //如果是新用户，将微信返回的信息存入数据库
                  var userinfo = wxcache.get("userInfo");
                  userinfo.mobile = wxcache.get("phoneNumber")                

                  util.request(api.InitUserInfo, userinfo, 'POST').then(function (res) {
                    console.log(res)
                  }).then(res=>{
                    util.request(api.QueryUserInfo, { mobile: wxcache.get("phoneNumber") })
                          .then(res=>{
                            wxcache.put("userInfo", res.responseBody );
                          })  
                  })
                }else{
                  //老用户从数据库取值
                  wxcache.put("userInfo", tmp)
                }
              },function(err){
                console.log(err)
              })
            
              wx.navigateBack()
              wx.showToast({
                title: '登陆成功',
                icon: 'succes',
                duration: 1000,
                mask: true
              })
              

              // //如果是老用户 并且设置过密码
              // user.checkSetPWD().then(function (res) {
                
                
              //   wx.showToast({
              //     title: '登陆成功',
              //     icon: 'succes',
              //     duration: 2000,
              //     mask: true
              //   })
              // }).catch(() => {
              //   wx.navigateTo({
              //     url: '/pages/auth/register/register',
              //   })
              // })
          })
        }
    })
  } ,
  bindUsernameInput: function (e) {

    this.setData({
      username: e.detail.value
    });
  },
  bindDyanmicCodeInput: function (e) {
    this.setData({
      dyanmicCode: e.detail.value
    });
  },
  bindPasswordInput: function (e) {

    this.setData({
      password: e.detail.value
    });
  },
  bindCodeInput: function (e) {

    this.setData({
      code: e.detail.value
    });
  },
  clearInput: function (e) {
    switch (e.currentTarget.id) {
      case 'clear-username':
        this.setData({
          username: ''
        });
        break;
      case 'clear-password':
        this.setData({
          password: ''
        });
        break;
      case 'clear-code':
        this.setData({
          code: ''
        });
        break;
    }
  },

  getDyanmicCode:function(){
    let that = this;
    var phone = that.data.username;
    
    if (!(/^1[34578]\d{9}$/.test(phone))) {

      wx.showModal({
        title: '错误信息',
        content: '请输入正确的手机号',
        showCancel: false
      });

      that.setData({
        ajxtrue: false
      })
      
    } else {

      that.setData({
        _num2: 0
      });

      that.setData({
        ajxtrue: true,
        dyanmicCodeNumber: that.data.dyanmicCodeNumbers,
        _num: 1
      })

      if (that.data.dyanmicCodeNumber<60){
        return;
      }

      var dyanmicNUmber = setInterval(function () {
        that.data.dyanmicCodeNumbers = that.data.dyanmicCodeNumbers - 1;
        if (that.data.dyanmicCodeNumbers == 0) {
          clearInterval(dyanmicNUmber);
          that.setData({
            dyanmicCodeNumbers: 60,
            _num2: 1
          })
          return;
        }
        that.setData({
          dyanmicCodeNumber: that.data.dyanmicCodeNumbers
        })
      }, 1000);

      util.request(api.SendMsg, { to: phone }, 'POST').then(function (res) {
        console.log(res)
        if (res.code == 200) {
          that.setData({
            seqNo: res.responseBody.seqNo,
            vcode: res.responseBody.vcode
          })
        } else {
          console.log('获取验证码失败');
          wx.showModal({
            title: '提示信息',
            content: '获取的频率太快了，请稍后再试~',
            showCancel: false
          });
        }
      })
    }
  },
  //根据验证码登陆
  loginByVCode: function () {
    var that = this;
    var data = {}
    data.mobile = this.data.username
    data.vcode = this.data.vcode
    data.seqNo = this.data.seqNo
    util.request(api.LoginURL, data, 'POST').then(function (res) {

      if (res.code == 200) {
        console.log("登陆成功")
        //登录成功进入用户资料页
        wxcache.put("phoneNumber", data.mobile)
        util.request(api.QueryUserInfo, { mobile: data.mobile }).then(function (res) {

          console.log(res)
          var usertmp = res.responseBody
          if (JSON.stringify(usertmp) != "{}") {
              //数据库可以取到userinfo， 则放入缓存
            if ( !usertmp.nickName || !usertmp.openId){
                usertmp = wxcache.get("userInfo")
       
                usertmp.mobile = wxcache.get("phoneNumber")

              util.request(api.InitUserInfo, usertmp, 'POST').then(function (res) {
                  console.log(res)
                }).then(res => {
                  util.request(api.QueryUserInfo, { mobile: wxcache.get("phoneNumber") })
                    .then(res => {
                      wxcache.put("userInfo", res.responseBody);
                    })
                })

              } 
          }

          //如果是老用户 并且设置过密码
          user.checkSetPWD().then(function (res) {
            wx.navigateBack()
            wx.showToast({
              title: '登陆成功',
              icon: 'succes',
              duration: 2000,
              mask: true
            })
          }).catch(() => {
            //老用户 未设置密码  + 新用户 进入设置密码页
            wx.navigateTo({
              url: '/pages/auth/register/register?username=' + that.data.username + '&dyanmicCodeNumber=' + that.data.dyanmicCodeNumber + '&seqNo=' + that.data.seqNo
            });
          })
        })
      } else {
        console.log("登陆失败")
      }
    })

  },
  startLogin:function(){
    var that = this;
    var data = {}
    data.mobile = this.data.username;
    data.vcode = this.data.dyanmicCode;
    data.seqNo = this.data.seqNo;

    if (!(/^1[34578]\d{9}$/.test(this.data.username))) {
      wx.showModal({
        title: '信息提示',
        content: '请输入正确的手机号',
        showCancel: false
      });
      return;
    }

    if (this.data._num0 == 0){
      if (this.data.password == '') {
        wx.showModal({
          title: '信息提示',
          content: '请输入密码',
          showCancel: false
        });
        return;
      }
      //密码登录
      this.loginByPwd();
    } else if (this.data._num0 == 1){
      if (this.data.dyanmicCode == '') {
        wx.showModal({
          title: '信息提示',
          content: '请输入验证码',
          showCancel: false
        });
        return;
      }
      
      util.request(api.verifyMsg, data, 'POST').then(function (res) {
        console.log(res)
        if (res.code == 200) {
          console.log('验证码有效')
          //验证码登录
          that.loginByVCode();
        } else {
          console.log('验证码无效')
          //提示验证码无效
          wx.showModal({
            title: '提示信息',
            content: '验证码无效，请输入正确验证码',
            showCancel: false
          });
          return;
        }
      })

    }
  },

  bindForgetPassword:function(){
    if (this.data._num0==0){
      this.setData({
        _num0: 1,
        forgetOrPasswordLoad: '密码登录',
        password:'',
      })
    } else if (this.data._num0 == 1){
      this.setData({
        _num0: 0,
        forgetOrPasswordLoad: '验证码登录',
        dyanmicCode:'',
      }) 
    }
  },
  
  //根据密码登陆
  loginByPwd:function(){
    var that = this;
    var data = {}
    data.mobile = this.data.username
    data.password = this.data.password
    
    util.request(api.LoginURL, data, 'POST').then(function (res) {
      console.log(res)
        if(res.code == 200){

          wxcache.put("phoneNumber", data.mobile)
          util.request(api.QueryUserInfo, { mobile: wxcache.get("phoneNumber") })
            .then(res => {
              wxcache.put("userInfo", res.responseBody);
          })

          wx.navigateBack()
          wx.showToast({
            title: '密码登陆成功',
            icon: 'succes',
            duration: 2000,
            mask: true
          }) 
        }else{
          console.log("登陆失败")
          //提示失败原因
          wx.showModal({
            title: '提示信息',
            content: res.responseBody,
            showCancel: false
          });
        }
        return res
    }).then(function(res){
      //未注册的手机号跳转验证码登陆
      if (res.code == 1017) {
        that.setData({
          _num0: 1,
          forgetOrPasswordLoad: '密码登录',
        })
      } 
    }) 


  }

})